var limit = 2 //每页显示2条
var page = 3 //第几页
var pages = 1 //一共多少页
var commentsLength = 0 //一共多少条评论
var comments = []
$('#messageBtn').on('click', function() {
  $.ajax({
    type: 'POST',
    url: '/api/comment/post',
    data: {
      contentid: $('#contentId').val(),
      content: $('#messageContent').val()
    },
    success: function(responseData) {
      $('#messageContent').val('')
      console.log(responseData)
      comments = responseData.data.comments.reverse()
      renderComment()
    }
  })
})

$.ajax({
  url: 'api/comment',
  data: {
    contentid: $('#contentId').val()
  },
  success: function(responseData) {
    comments = responseData.data.reverse()
    renderComment()
  }
})

function renderComment() {
  commentsLength = comments.length
  pages = Math.ceil(commentsLength / limit)
  let start = Math.max((page - 1) * limit, 0)
  let end = Math.min(page * limit, commentsLength)
  page1()
  $('#messageCount').html(comments.length) //修改评论数量 一共多少条评论

  let $lis = $('.clear li')
  console.log($lis.eq(1))
  $lis.eq(1).html(page + ' / ' + pages)

  var html = ''
  for (var i = start; i < end; i++) {
    html += `<div class="messageBox">
        <p class="name clear">
        <span class="fl">${comments[i].username}</span>
        <span class="fr">${formatDate(comments[i].postTime)}</span>
        </p>
        <p>${comments[i].content}</p>

    </div>`
  }
  $('.messageList').html(html)
}
$('.previous').on('click', function() {
  page--
  page = Math.max(1, page)
  renderComment()
})

$('.next').on('click', function() {
  page++
  page = Math.min(pages, page)
  renderComment()
})

function page1() {
  if (page <= 1) {
    page = 1
    $('.previous').html('<span>没有上一页了</span>')
    $('.next').html('<a href="javascript:;">下一页</a>')
  } else if (page >= pages) {
    page = pages
    $('.previous').html(' <a href="javascript:;">上一页</a>')
    $('.next').html('<span>没有下一页了</span>')
  } else {
    $('.previous').html(' <a href="javascript:;">上一页</a>')
    $('.next').html('<a href="javascript:;">下一页</a>')
  }
}
function formatDate(time) {
  var date1 = new Date(time)
  return (
    date1.getFullYear() +
    '年' +
    (date1.getMonth() + 1) +
    '月' +
    date1.getDate() +
    '日' +
    date1.getHours() +
    ':' +
    date1.getMinutes() +
    ':' +
    date1.getSeconds()
  )
}
